package com.htfyun.roobofactory.factorytest;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.htfyun.roobofactory.R;

/**
 * Created by sst on 2018/5/30.
 */

public class FactoryPreviousItemFloatWindowService extends Service
        implements View.OnTouchListener, View.OnClickListener {

    private static final String TAG = "FTFloatWindowService";
    private View mFloatLayout = null;
    private WindowManager.LayoutParams wmParams;
    private WindowManager mWindowManager;
    private Button btnPrevious;
    private Button btnReturn;

    private Context context;

    //触摸监听器
    GestureDetector mGestureDetector;

    private static int lastWindowX = -1;
    private static int lastWindowY = -1;


    public static final String ACTION_FACTORY_PREVIOUS_CLICKED = "action.roboo.factorytest.previous_clicked";
    public static final String ACTION_FACTORY_RETURN_CLICKED = "action.roboo.factorytest.return_clicked";

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        Log.e(TAG, "onCreate");
        context = this;
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        addFloatView();

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        Log.e(TAG, "onDestroy");

        removeFloatView();
    }

    private void removeFloatView() {
        if (mFloatLayout != null) {
            //移除悬浮窗口
            mWindowManager.removeView(mFloatLayout);
            mFloatLayout = null;
        }
    }

    private void addFloatView() {

        if (mFloatLayout != null) {
            return;
        }

        wmParams = new WindowManager.LayoutParams();
        //获取的是WindowManagerImpl.CompatModeWrapper
        mWindowManager = (WindowManager)getApplication().getSystemService(getApplication().WINDOW_SERVICE);
        Log.e(TAG, "mWindowManager--->" + mWindowManager);
        //设置window type
        if (Build.VERSION.SDK_INT >= 24) { /*android7.0不能用TYPE_TOAST*/
            wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        } else { /*以下代码块使得android6.0之后的用户不必再去手动开启悬浮窗权限*/
            String packname = context.getPackageName();
            PackageManager pm = context.getPackageManager();
            boolean permission = (PackageManager.PERMISSION_GRANTED == pm.checkPermission("android.permission.SYSTEM_ALERT_WINDOW", packname));
            if (permission) {
                wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
            } else {
                wmParams.type = WindowManager.LayoutParams.TYPE_TOAST;
            }
        }

        //设置图片格式，效果为背景透明
        wmParams.format = PixelFormat.RGBA_8888;
        //设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
//        wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        //设置可以显示在状态栏上
        wmParams.flags =  WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL|
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN| WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR|
                WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;

        //调整悬浮窗显示的停靠位置为左侧置顶
        wmParams.gravity = Gravity.START| Gravity.TOP;


        if (lastWindowX < 0 || lastWindowY < 0) {
            Point point = new Point();
            mWindowManager.getDefaultDisplay().getSize(point);
            // 以屏幕左上角为原点，设置x、y初始值，相对于gravity
            wmParams.x = point.x / 2;
            wmParams.y = point.y - 150;
        } else {
            wmParams.x = lastWindowX;
            wmParams.y = lastWindowY;
        }


        Log.e(TAG, " lastWindowX = " + lastWindowX + ", lastWindowY = " + lastWindowY);

        //设置悬浮窗口长宽数据
        wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;

        LayoutInflater inflater = LayoutInflater.from(getApplication());
        //获取浮动窗口视图所在布局
        mFloatLayout = inflater.inflate(R.layout.factory_previous_float_layout, null);
        //添加mFloatLayout
        mWindowManager.addView(mFloatLayout, wmParams);
        //浮动窗口按钮
        btnPrevious = (Button)mFloatLayout.findViewById(R.id.btnPrevious);
        btnReturn = (Button) mFloatLayout.findViewById(R.id.btnReturn);

        mFloatLayout.measure(View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
                .makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        Log.e(TAG, "Width/2--->" + btnPrevious.getMeasuredWidth()/2);
        Log.e(TAG, "Height/2--->" + btnPrevious.getMeasuredHeight()/2);
        //设置监听浮动窗口的触摸移动

        mGestureDetector = new GestureDetector(this, new MyOnGestureListener());
        btnPrevious.setOnTouchListener(this);
        btnPrevious.setOnClickListener(this);
        btnReturn.setOnTouchListener(this);
        btnReturn.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        Log.e(TAG, "onclick v = " + v);
        if (mFloatLayout == null) {
            return;
        }
        String action = null;
        if (v == btnPrevious) {
            action = ACTION_FACTORY_PREVIOUS_CLICKED;
        } else if (v == btnReturn) {
            action = ACTION_FACTORY_RETURN_CLICKED;
        }
        if (action != null) {
            Intent intent = new Intent(action);
            sendBroadcast(intent);
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        Log.e(TAG, "onTouch v = " + v);
        if (mFloatLayout == null) {
            return false;
        }
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                isMove = false;
                mTouchStartX = (int)event.getRawX();
                mTouchStartY = (int)event.getRawY();
                mStartX = wmParams.x;//(int)event.getX();
                mStartY = wmParams.y;//(int)event.getY();
                break;

            case MotionEvent.ACTION_MOVE:

                mTouchCurrentX = (int) event.getRawX();
                mTouchCurrentY = (int) event.getRawY();
                wmParams.x += mTouchCurrentX - mTouchStartX;
                wmParams.y += mTouchCurrentY - mTouchStartY;
                mWindowManager.updateViewLayout(mFloatLayout, wmParams);

                mTouchStartX = mTouchCurrentX;
                mTouchStartY = mTouchCurrentY;
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:

                mStopX = wmParams.x;//(int)event.getX();
                mStopY = wmParams.y;//(int)event.getY();
                if(Math.abs(mStartX - mStopX) >= 5 || Math.abs(mStartY - mStopY) >= 5){
                    isMove = true;
                }

                break;
        }

        lastWindowX = wmParams.x;
        lastWindowY = wmParams.y;

        return mGestureDetector.onTouchEvent(event) || isMove;
    }

    //开始触控的坐标，移动时的坐标（相对于屏幕左上角的坐标）
    private int mTouchStartX,mTouchStartY,mTouchCurrentX,mTouchCurrentY;
    //开始时的坐标和结束时的坐标（相对于自身控件的坐标）
    private int mStartX,mStartY,mStopX,mStopY;
    private boolean isMove;//判断悬浮窗是否移动

    /**
     * http://www.cnblogs.com/tianzhijiexian/p/3994546.html
     * @author:金凯
     * @tips  :自己定义的手势监听类
     * @date  :2014-3-29
     */
    class MyOnGestureListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
//            if (!isMove) {
//                Toast.makeText(getApplicationContext(), "你点击了悬浮窗", Toast.LENGTH_SHORT).show();
//            }
            return super.onSingleTapConfirmed(e);
        }


    }
}
